package com.fjp.heartguard.ui.question

import android.content.Intent
import android.content.res.Configuration
import android.os.Bundle
import android.widget.ImageView
import com.fjp.heartguard.R
import com.fjp.heartguard.app.Constants
import com.fjp.heartguard.app.base.BaseActivity
import com.fjp.heartguard.app.data.bean.GroupQuestionType
import com.fjp.heartguard.app.data.bean.OlderInfo
import com.fjp.heartguard.app.data.bean.OlderInfoQuestion
import com.fjp.heartguard.app.data.bean.Options
import com.fjp.heartguard.app.data.bean.QuestionType
import com.fjp.heartguard.app.data.bean.Questions
import com.fjp.heartguard.app.data.bean.Select
import com.fjp.heartguard.app.eventViewModel
import com.fjp.heartguard.app.ext.showToast
import com.fjp.heartguard.databinding.ActivityQuestionBinding
import com.fjp.heartguard.ui.question.adapter.QuestionAdapter
import com.fjp.heartguard.ui.question.fragment.CognitiveAssessment3Fragment
import com.fjp.heartguard.ui.question.fragment.InputFragment
import com.fjp.heartguard.ui.question.fragment.MultipleFragment
import com.fjp.heartguard.ui.question.fragment.SeekBarFragment
import com.fjp.heartguard.ui.question.fragment.SingleInputFragment
import com.fjp.heartguard.ui.question.fragment.SingleSelectedFragment
import com.fjp.heartguard.viewmodel.QuestionViewModel
import com.lxj.xpopup.XPopup
import com.zlw.main.recorderlib.RecordManager
import com.zlw.main.recorderlib.recorder.RecordHelper.RecordState
import me.hgj.jetpackmvvm.ext.util.isPhone
import kotlin.random.Random

class QuestionActivity : BaseActivity<QuestionViewModel, ActivityQuestionBinding>() {
    lateinit var adapter: QuestionAdapter
    var questionIndex: Int = 0

    companion object {
        var questions = mutableListOf<Questions>()
        var olderInfo = OlderInfo(0, "", "男", "", "", "", "", "", "", "家", "", "", "", "", "", mutableListOf())
        var olderInfoQuestion1 = OlderInfoQuestion("A组：袜子、红色、茶几", arrayListOf(Select("重复正确", 0, ""), Select("错误", 0, "")))
        var olderInfoQuestion2 = OlderInfoQuestion("B组：床、上衣、蓝色", arrayListOf(Select("重复正确", 0, ""), Select("错误", 0, "")))
        var olderInfoQuestion3 = OlderInfoQuestion("C组：绿色、桌子、鞋子", arrayListOf(Select("重复正确", 0, ""), Select("错误", 0, "")))
        var olderInfoQuestion4 = OlderInfoQuestion("现在是哪一年？", arrayListOf(Select("", 0, "")))
        var olderInfoQuestion5 = OlderInfoQuestion("今天是几月几号？", arrayListOf(Select("", 0, "")))
        var olderInfoQuestion6 = OlderInfoQuestion("今天星期几？", arrayListOf(Select("", 0, "")))
        var olderInfoQuestion7 = OlderInfoQuestion("A组：袜子、红色、茶几", arrayListOf(Select("重复正确", 0, ""), Select("提示后正确", 0, ""), Select("错误", 0, "")))
        var olderInfoQuestion8 = OlderInfoQuestion("B组：床、上衣、蓝色", arrayListOf(Select("重复正确", 0, ""), Select("提示后正确", 0, ""), Select("错误", 0, "")))
        var olderInfoQuestion9 = OlderInfoQuestion("C组：绿色、桌子、鞋子", arrayListOf(Select("重复正确", 0, ""), Select("提示后正确", 0, ""), Select("错误", 0, "")))
        var jumpB = false//是否跳过了认知评估A
        var hasVoice = true//是否有录音
        var yearIsChecked = false//认知评估A，现在是哪一年用户是不是选择了无法作答
        var monthIsChecked = false//认知评估A，现在是几月几号用户是不是选择了无法作答
        var weekIsChecked = false//认知评估A，现在是星期几用户是不是选择了无法作答
        var curSpanIndex1 = 0
        var curSpanIndex2 = 1
        var curSpanIndex3 = 2
        var times = 1

    }

    override fun initView(savedInstanceState: Bundle?) {
        olderInfoQuestion1.select.forEach { it.is_selected = 0 }
        olderInfoQuestion2.select.forEach { it.is_selected = 0 }
        olderInfoQuestion3.select.forEach { it.is_selected = 0 }
        olderInfoQuestion4.select.forEach { it.value = ""; it.unanswerable = 0 }
        olderInfoQuestion5.select.forEach { it.value = ""; it.unanswerable = 0 }
        olderInfoQuestion6.select.forEach { it.value = ""; it.unanswerable = 0 }
        olderInfoQuestion7.select.forEach { it.is_selected = 0 }
        olderInfoQuestion8.select.forEach { it.is_selected = 0 }
        olderInfoQuestion9.select.forEach { it.is_selected = 0 }
        curSpanIndex1 = Random.nextInt(0, 3)
        if (curSpanIndex1 == 0) {
            if (times % 2 == 0) {
                curSpanIndex2 = 2
                curSpanIndex3 = 1
            } else {
                curSpanIndex2 = 0
                curSpanIndex3 = 0
            }


        } else if (curSpanIndex1 == 1) {
            if (times % 2 == 0) {
                curSpanIndex2 = 0
                curSpanIndex3 = 2
            } else {
                curSpanIndex2 = 1
                curSpanIndex3 = 1
            }

        } else {
            if (times % 2 == 0) {
                curSpanIndex2 = 1
                curSpanIndex3 = 0
            } else {
                curSpanIndex2 = 2
                curSpanIndex3 = 2
            }
        }
        times++
        yearIsChecked = false
        monthIsChecked = false
        weekIsChecked = false
        mDatabind.viewModel = mViewModel
        mDatabind.click = ClickProxy()
        mViewModel.title.set(getString(R.string.question_title))
        val olderInfo = intent.getParcelableExtra<OlderInfo>(Constants.Intent_REPORT)
        if (olderInfo != null) {
            QuestionActivity.olderInfo = OlderInfo(0, olderInfo.name, olderInfo.sex, olderInfo.mobile, olderInfo.birthday, olderInfo.province, olderInfo.city, olderInfo.district, olderInfo.address, olderInfo.live_type, olderInfo.institution_name, "", "", "", "", mutableListOf())
        } else {

            QuestionActivity.olderInfo = OlderInfo(0, "", "男", "", "", "", "", "", "", "家", "", "", "", "", "", mutableListOf())
        }
        questions = mutableListOf<Questions>()


        adapter = QuestionAdapter(supportFragmentManager)
        mDatabind.viewpager.adapter = adapter
        for (i in 1 until 90) {
            val arrayID = getResId("q${i}")
            if (arrayID == 0) {
                continue
            }
            val questionStr = resources.getStringArray(arrayID)
            val question = Questions()
            setQuestionType(question, i)
            for ((index, s) in questionStr.withIndex()) {
                if (index == 0) {
                    question.questionTitle = s
                } else if (index == 1) {
                    if (s == "0") {
                        adapter.addFragment(SingleSelectedFragment.newInstance(question))
                    } else if (s == "1") {
                        question.type = QuestionType.MULTIPLE
                        adapter.addFragment(MultipleFragment.newInstance(question))
                    } else if (s == "2") {
                        question.type = QuestionType.PROGRESSBAR
                        adapter.addFragment(SeekBarFragment.newInstance(question))
                    } else if (s == "3") {
                        question.type = QuestionType.INPUT
                        adapter.addFragment(InputFragment.newInstance(question))
                    } else if (s == "4") {
                        question.type = QuestionType.SINGINPUT
                        adapter.addFragment(SingleInputFragment.newInstance(question))
                    }
                } else {
                    question.options.add(Options(s, false, ""))
                }

            }
            questions.add(question)
        }

        mDatabind.qpb.setValue(mDatabind.viewpager.currentItem, adapter.count, hasVoice)

    }

    override fun onResume() {
        super.onResume()
        //不能删除。监听返回按钮弹框提示用户
        findViewById<ImageView>(R.id.backIv)?.setOnClickListener {
            showGoBack()
        }
    }

    private fun showGoBack() {
        XPopup.Builder(this).asConfirm("提示", "确定要退出当前问卷吗？", "取消", "确定", {
            finish()
        }, {}, false).show()
    }

    private fun setQuestionType(question: Questions, i: Int) {
        if (i < 6) {
            question.questionType = GroupQuestionType.COGNITION_B
        } else if (i in 6..9) {
            question.questionType = GroupQuestionType.LOCOMOTIVITY
        } else if (i in 10..13) {
            question.questionType = GroupQuestionType.NUTRITIONAL_STATUS
        } else if (i in 14..18) {
            question.questionType = GroupQuestionType.SENSORY_ABILITY
        } else if (i in 19..20) {
            question.questionType = GroupQuestionType.DEPRESSED
        } else if (i in 21..22) {
            question.questionType = GroupQuestionType.DEFECATION
        } else if (i in 23..29) {
            question.questionType = GroupQuestionType.DAILY_LIFE_A
        } else if (i in 30..37) {
            question.questionType = GroupQuestionType.DAILY_LIFE_B
        } else if (i in 38..59) {
            question.questionType = GroupQuestionType.TAKE_CARE_OF
        } else if (i in 60..74) {
            question.questionType = GroupQuestionType.CARE_SERVICES
        } else if(i in 88 .. 89){
            question.questionType = GroupQuestionType.STATISTICS
        }else {
            question.questionType = GroupQuestionType.MEDICAL_SERVICE
        }
    }

    override fun createObserver() {
        super.createObserver()
        eventViewModel.jumpB.observeInActivity(this) {
            jumpB = true
            mDatabind.viewpager.currentItem = 4
        }
        eventViewModel.saveQuestionSuccess.observeInActivity(this) {
            finish()
        }
        eventViewModel.nextFragment.observeInActivity(this) {
            mDatabind.click!!.clickNext()
        }
    }

    inner class ClickProxy {
        fun clickPre() {
            if (mDatabind.viewpager.currentItem == 0) {
                showLogoutPop()
                return
            }
            if (mDatabind.viewpager.currentItem == 4) {
                mDatabind.viewpager.currentItem = if (jumpB) 1 else mDatabind.viewpager.currentItem - 1
            } else if (mDatabind.viewpager.currentItem == 9) {
                mDatabind.viewpager.currentItem = if (jumpB) mDatabind.viewpager.currentItem - 1 else 3
            } else if (mDatabind.viewpager.currentItem == 47 && questions[40].options[1].isSelected) {//是否有压疮选项，如果选否调至46题
                mDatabind.viewpager.currentItem = 44
            } else if (mDatabind.viewpager.currentItem == 49) {//是否有压疮选项，如果选否调至46题
                if(questions[5].options[4].isSelected && questions[40].options[1].isSelected){
                    mDatabind.viewpager.currentItem = 44
                }else if(questions[5].options[4].isSelected)
                    mDatabind.viewpager.currentItem = 46
                else{
                    mDatabind.viewpager.currentItem = 48
                }

            } else if (mDatabind.viewpager.currentItem == 54 && questions[45].options[1].isSelected) {//是否存在慢性疼痛,否跳转到54
                mDatabind.viewpager.currentItem = 49
            } else if (mDatabind.viewpager.currentItem == 54 && questions[48].options[1].isSelected) {//是否接受疼痛管理，否跳转54
                mDatabind.viewpager.currentItem = 52
            } else if (mDatabind.viewpager.currentItem == 59 && questions[50].options[1].isSelected) {//是否接受疼痛管理，否跳转54
                mDatabind.viewpager.currentItem = 54
            } else if (mDatabind.viewpager.currentItem == 65 && QuestionActivity.olderInfo.live_type != "养老机构") {
                mDatabind.viewpager.currentItem = 62
            }  else if (mDatabind.viewpager.currentItem == 71 && questions[62].options[1].isSelected) {//是否家庭成员为您提供照顾？否跳转71
                mDatabind.viewpager.currentItem = 66
            } else if (mDatabind.viewpager.currentItem == 78 && questions[59].options[1].isSelected) {//是否有压疮选项，如果选否调至46题
                mDatabind.viewpager.currentItem = 63
            } else if (mDatabind.viewpager.currentItem == 78 && (questions[60].options.filter { it.isSelected }.size > 0)) {//家人陪伴，选着后直接跳转78题，由于没有养老机构选项数字比题上的数字小1
                mDatabind.viewpager.currentItem = 64
            } else if (mDatabind.viewpager.currentItem == 78 && questions[61].options[1].isSelected) {//是否有人为您提供照料，否跳转78
                mDatabind.viewpager.currentItem = 65
            } else if (mDatabind.viewpager.currentItem == 78 && questions[67].options[1].isSelected) {//是否使用过任何付费服务
                mDatabind.viewpager.currentItem = 71
            } else if (mDatabind.viewpager.currentItem == 78 && questions[72].options[0].isSelected) {//如果76是完全满足，应该跳转76
                mDatabind.viewpager.currentItem = 76
            }  else if (mDatabind.viewpager.currentItem == 82 && questions[75].options[1].isSelected) {//过去两周内是否去过医院急诊，否跳转82
                mDatabind.viewpager.currentItem = 79
            } else if (mDatabind.viewpager.currentItem == 86 && questions[78].options[2].isSelected) {//过去两周是否进行过门诊就诊，否跳转86
                mDatabind.viewpager.currentItem = 82
            } else if (mDatabind.viewpager.currentItem == 91 && questions[82].options[1].isSelected) {
                mDatabind.viewpager.currentItem = 86
            }else {
                mDatabind.viewpager.currentItem = mDatabind.viewpager.currentItem - 1
            }
            mDatabind.qpb.setValue(mDatabind.viewpager.currentItem, adapter.count, hasVoice)
        }

        fun clickNext() {

            if (QuestionActivity.olderInfo.name.trim().isEmpty()) {
                showToast("请输入姓名")
                return
            } else if (QuestionActivity.olderInfo.birthday.trim().isEmpty()) {
                showToast("请选择出生日期")
                return
            } else if (QuestionActivity.olderInfo.mobile.trim().isEmpty()) {
                showToast("请输入手机号")
                return
            } else if (!QuestionActivity.olderInfo.mobile.trim().isPhone()) {
                showToast("请输入正确手机号")
                return
            } else if (QuestionActivity.olderInfo.province.trim().isEmpty()) {
                showToast("请选择居住地")
                return
            } else if (QuestionActivity.olderInfo.address.trim().isEmpty()) {
                showToast("请输入详细地址")
                return
            }

            if (mDatabind.viewpager.currentItem == 1) {
                var isSelected = false
                for ((index, options) in olderInfoQuestion1.select.withIndex()) {
                    if (options.is_selected == 1) {
                        isSelected = true
                    }
                }

                if (!isSelected) {
                    showToast("请选择选项A组选项")
                    return
                }
                isSelected = false
                for ((index, options) in olderInfoQuestion2.select.withIndex()) {
                    if (options.is_selected == 1) {
                        isSelected = true
                    }
                }

                if (!isSelected) {
                    showToast("请选择选项B组选项")
                    return
                }
                isSelected = false
                for ((index, options) in olderInfoQuestion3.select.withIndex()) {
                    if (options.is_selected == 1) {
                        isSelected = true
                    }
                }

                if (!isSelected) {
                    showToast("请选择选项C组选项")
                    return
                }
            } else if (mDatabind.viewpager.currentItem == 2) {
                if (olderInfoQuestion4.select[0].unanswerable == 0 && olderInfoQuestion4.select[0].value.isEmpty()) {
                    showToast("请选择现在是哪一年或无法作答")
                    return
                } else if (olderInfoQuestion5.select[0].unanswerable == 0 && olderInfoQuestion5.select[0].value.isEmpty()) {
                    showToast("请选择现在是几月几号或无法作答")
                    return
                } else if (olderInfoQuestion6.select[0].unanswerable == 0 && olderInfoQuestion6.select[0].value.isEmpty()) {
                    showToast("请选择现在是星期几或无法作答")
                    return
                }
            } else if (mDatabind.viewpager.currentItem == 3) {
                var isSelected = false
                for ((index, options) in olderInfoQuestion7.select.withIndex()) {
                    if (options.is_selected == 1) {
                        isSelected = true
                    }
                }

                if (!isSelected) {
                    showToast("请选择选项A组选项")
                    return
                }
                isSelected = false
                for ((index, options) in olderInfoQuestion8.select.withIndex()) {
                    if (options.is_selected == 1) {
                        isSelected = true
                    }
                }

                if (!isSelected) {
                    showToast("请选择选项B组选项")
                    return
                }
                isSelected = false
                for ((index, options) in olderInfoQuestion9.select.withIndex()) {
                    if (options.is_selected == 1) {
                        isSelected = true
                    }
                }

                if (!isSelected) {
                    showToast("请选择选项C组选项")
                    return
                }
            } else if (mDatabind.viewpager.currentItem >= 4 && (questions[mDatabind.viewpager.currentItem - 4].type == QuestionType.SINGLE || questions[mDatabind.viewpager.currentItem - 4].type == QuestionType.MULTIPLE)) {
                var isSelected = false
                var selectedOther = false
                for ((index, options) in questions[mDatabind.viewpager.currentItem - 4].options.withIndex()) {
                    if (options.isSelected) {
                        isSelected = true
                    }
                    if (options.isSelected && options.title.startsWith("*") && options.value.isEmpty()) {
                        selectedOther = true
                    }
                }

                if (!isSelected) {
                    showToast("请选择选项再执行下一步操作")
                    return
                }
                if (selectedOther) {
                    showToast("请输入详细内容")
                    return
                }
            } else if (mDatabind.viewpager.currentItem > 4 && questions[mDatabind.viewpager.currentItem - 4].type == QuestionType.SINGINPUT || mDatabind.viewpager.currentItem > 4 && questions[mDatabind.viewpager.currentItem - 4].type == QuestionType.INPUT) {
                if (questions[mDatabind.viewpager.currentItem - 4].options[0].value.isEmpty()) {
                    showToast("请输入内容")
                    return
                }

            }
            if (mDatabind.viewpager.currentItem == 3 && (adapter.getItem(3) is CognitiveAssessment3Fragment)) {
                jumpB = false
                mDatabind.viewpager.currentItem = mDatabind.viewpager.currentItem + 6
            } else if (mDatabind.viewpager.currentItem == adapter.count - 1) {
                startActivity(Intent(this@QuestionActivity, QuestionSupplementaryInfoActivity::class.java))
            } else if (mDatabind.viewpager.currentItem == 44 && questions[mDatabind.viewpager.currentItem - 4].options[1].isSelected) {//是否有压疮选项，如果选否调至46题
                if (questions[5].options[4].isSelected) {//如果9题选择了可以独立翻身就跳转49，跳过47、48
                    mDatabind.viewpager.currentItem = 49
                } else {
                    mDatabind.viewpager.currentItem = 47
                }
            } else if (mDatabind.viewpager.currentItem == 46 && questions[5].options[4].isSelected) {//是否有压疮选项，如果选否调至46题
                mDatabind.viewpager.currentItem = 49
            } else if (mDatabind.viewpager.currentItem == 49 && questions[mDatabind.viewpager.currentItem - 4].options[1].isSelected) {//是否存在慢性疼痛,否跳转到54
                mDatabind.viewpager.currentItem = 54
            } else if (mDatabind.viewpager.currentItem == 52 && questions[mDatabind.viewpager.currentItem - 4].options[1].isSelected) {//是否接受疼痛管理，否跳转54
                mDatabind.viewpager.currentItem = 54
            } else if (mDatabind.viewpager.currentItem == 54 && questions[mDatabind.viewpager.currentItem - 4].options[1].isSelected) {//是否接受疼痛管理，否跳转54
                mDatabind.viewpager.currentItem = 59
            } else if (mDatabind.viewpager.currentItem == 62) {
                mDatabind.viewpager.currentItem = if (QuestionActivity.olderInfo.live_type == "养老机构") 63 else 65
            } else if (mDatabind.viewpager.currentItem == 63 && questions[mDatabind.viewpager.currentItem - 4].options[1].isSelected) {//是否有压疮选项，如果选否调至46题
                mDatabind.viewpager.currentItem = 78
            } else if (mDatabind.viewpager.currentItem == 64) {//家人陪伴次数，选着后直接跳转78题，由于没有养老机构选项数字比题上的数字小1
                mDatabind.viewpager.currentItem = 78
            } else if (mDatabind.viewpager.currentItem == 65) {//是否有人为您提供照料，否跳转78
                mDatabind.viewpager.currentItem = if (questions[mDatabind.viewpager.currentItem - 4].options[1].isSelected) 78 else 66
            } else if (mDatabind.viewpager.currentItem == 66) {//是否家庭成员为您提供照顾？否跳转71
                mDatabind.viewpager.currentItem = if (questions[mDatabind.viewpager.currentItem - 4].options[1].isSelected) 71 else 67
            } else if (mDatabind.viewpager.currentItem == 71) {//是否使用过任何付费服务
                mDatabind.viewpager.currentItem = if (questions[mDatabind.viewpager.currentItem - 4].options[1].isSelected) 78 else 72
            } else if (mDatabind.viewpager.currentItem == 76 && questions[mDatabind.viewpager.currentItem - 4].options[0].isSelected) {//是否完全满足，完全满足跳到78
                mDatabind.viewpager.currentItem = 78
            } else if (mDatabind.viewpager.currentItem == 79) {//过去两周内是否去过医院急诊，否跳转82
                mDatabind.viewpager.currentItem = if (questions[mDatabind.viewpager.currentItem - 4].options[1].isSelected) 82 else 80
            } else if (mDatabind.viewpager.currentItem == 82) {//过去两周是否进行过门诊就诊，否跳转86
                mDatabind.viewpager.currentItem = if (questions[mDatabind.viewpager.currentItem - 4].options[2].isSelected) 86 else 83
            } else if (mDatabind.viewpager.currentItem == 86 && questions[mDatabind.viewpager.currentItem - 4].options[1].isSelected) {//过去三个月内是否有住院经历，否跳结束
                mDatabind.viewpager.currentItem = 91

                return
            } else if (mDatabind.viewpager.currentItem == 91 ) {//过去三个月内是否有住院经历，否跳结束
                if(!questions[mDatabind.viewpager.currentItem - 4].options[0].isSelected){
                    mDatabind.viewpager.currentItem = 92
                }else{
                    startActivity(Intent(this@QuestionActivity, QuestionSupplementaryInfoActivity::class.java))
                }

                return
            } else {
                mDatabind.viewpager.currentItem = mDatabind.viewpager.currentItem + 1
            }
            mDatabind.qpb.setValue(mDatabind.viewpager.currentItem, adapter.count, hasVoice)

        }

    }

    fun getResId(name: String): Int {
        val id = resources.getIdentifier(name, "array", packageName)
        return id
    }

    override fun onBackPressed() {
        if (mDatabind.viewpager.currentItem == 0) {
            if (RecordManager.getInstance().state == RecordState.RECORDING) {
                RecordManager.getInstance().stop()
            }
            finish()
        }
    }

    private fun showLogoutPop() {
        XPopup.Builder(this).asConfirm("提示", "是否退出当前评估问卷", "取消", "确定", {
            finish()
        }, {}, false).show()
    }

    override fun onConfigurationChanged(newConfig: Configuration) {
        super.onConfigurationChanged(newConfig)
        // Checks the orientation of the screen
        if (newConfig.orientation === Configuration.ORIENTATION_LANDSCAPE) {
            // 横屏处理逻辑
            println("横屏============")
        } else if (newConfig.orientation === Configuration.ORIENTATION_PORTRAIT) {
            // 竖屏处理逻辑
            println("竖屏============")
        }
    }

}
